<template>
  <!-- 商家版   货源配置  供货人配置 -->
  <el-dialog class :title="'配置供货商'" :visible.sync="dialogVisible" :close-on-click-modal="false" fullscreen>
    <div class="supply-config-page bgf">
      <div class="" v-loading="loading">
        <el-form :model="ruleForm" ref="ruleForm" label-width="auto" class="demo-ruleForm">
          <div class="subtit">
            <formSubTit :title="'游戏：'+curGame.name"></formSubTit>
          </div>
          <div class="subtit">
            <formSubTit :title="'选择供货人'" :tip="'请将需要的供货人勾选上，更改完毕请点击底部提交按钮'"></formSubTit>
          </div>
          <div  >
            <div style="margin-bottom: 10px;">
              <el-input style="width: 200px;" placeholder="请输入供货人名称"  clearable v-model="filterParams.supplyName"></el-input>
              <el-select v-model="filterParams.shoudong" placeholder="请选择上架类型" clearable  >
                <el-option label="手动上架" :value="1" />
                <el-option label="API上架" :value="2" />
              </el-select>
              <el-select v-model="filterParams.isSelf" placeholder="请选择经营类型" clearable  >
                <el-option label="自营" :value="1" />
                <el-option label="代售" :value="2" />
              </el-select>
              <span style="margin-left: 15px;">
                <el-button type="primary" @click="search" size="big">搜索</el-button>
                <el-button type="warning" plain @click="resetSearch" size="big">重置</el-button>
              </span>
            </div>
            <div class="table_box table_box_new" v-if="supplyList&&supplyList.length">
              <el-table  :default-sort = "{prop: 'odr', order: 'ascending'}" stripe border ref="multipleTable" height="calc(100vh - 300px)" :data="supplyList" style="width: 100%" @selection-change="handleSelectionChange">
                <!-- :selectable="getDisabledRows" -->
                <el-table-column type="selection" label="全选" width="70"></el-table-column>
                <el-table-column label="供货人" width="150">
                  <template slot-scope="scope">
                    <!-- {{ scope.row.tenant_name }} -->
                    <div v-if="allYouzhiMap&&allYouzhiMap[scope.row.tenant_id]">
                      <youzhiName :name="scope.row.tenant_name"></youzhiName>
                    </div>
                    <div v-else>
                      {{ scope.row.tenant_name }}
                    </div>

                  </template>
                </el-table-column>
                <el-table-column label="供货折扣" width="100">
                  <template slot-scope="scope">
                    <div >
                      {{ scope.row.supplyRise ||10}}折
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="商品数量" width="260" prop="ziyingCot">
                  <template slot-scope="scope">
                    <div class="flex" style="text-align: left !important;">
                      <div style="margin-right: 20px;">
                        <div>手动上架：{{scope.row.ziyingCot||0}}</div>
                        <div>api上架：{{scope.row.apiCot||0}}</div>
                      </div>
                      <div>
                        <div>自营商品：{{scope.row.ifself1Cot||0}}</div>
                        <div>代售商品：{{scope.row.ifself2Cot||0}}</div>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <!-- <el-table-column label="api上架" width="100" prop="apiCot"></el-table-column> -->
                <el-table-column sortable prop="odr" label="排序" width="110">
                  <template slot-scope="scope">
                    <el-input-number :controls="false" :disabled="scope.row.isDisabled" :precision="0" :step="1" v-model="scope.row.odr" placeholder="序号" :max="9999">
                    </el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="固定加价" width="130">
                  <template slot="header">
                    <el-tooltip class="item" effect="dark" content="请输入固定的加价金额，加价公式：固定加价+供货价x加价百分比">
                      <span class="el-icon-question"></span>
                    </el-tooltip>
                    固定加价
                  </template>
                  <template slot-scope="scope">
                    <el-input style="width:100px" :disabled="scope.row.isDisabled" @change="numchange($event, scope.row)" :precision="0" v-model="scope.row.gudingjiajia" placeholder="请输入数字" maxlength="5">
                      <span slot="suffix" style="line-height: 36px;">
                        元
                      </span>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="加价百分比" width="160">
                  <template slot="header">
                    <el-tooltip class="item" effect="dark" content="请输入加价百分比，加价公式：固定加价+供货价x加价百分比">
                      <span class="el-icon-question"></span>
                    </el-tooltip>
                    加价百分比
                  </template>
                  <template slot-scope="scope">
                    <el-input-number style="width:130px" :disabled="scope.row.isDisabled" @change="numchange($event, scope.row)" :step="1" :precision="0" v-model="scope.row.rrise" placeholder="请输入" maxlength="3"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="上架类型" width="110">
                  <template slot-scope="scope">
                    <el-radio-group :disabled="scope.row.isDisabled" v-model="scope.row.accountType">
                      <el-radio :label="3">全部</el-radio>
                      <el-radio :label="1">手动上架</el-radio>
                      <el-radio :label="2">api上架</el-radio>
                    </el-radio-group>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="商品类型" width="110">
                  <template slot-scope="scope">
                    <el-radio-group :disabled="scope.row.isDisabled" v-model="scope.row.ifself">
                      <el-radio :label="3">全部</el-radio>
                      <el-radio :label="1">自营</el-radio>
                      <el-radio :label="2">代售</el-radio>
                    </el-radio-group>
                  </template>
                </el-table-column>
                <el-table-column label="联系方式" prop="phonenumber" width="120">
                  <template slot-scope="scope">
                    <span>
                     {{scope.row.lianxishouji|| scope.row.phonenumber }}
                    </span><br/>
                    <span v-if="scope.row.lianxiweixin">
                      微信:{{scope.row.lianxiweixin }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="自营商城" width="100" prop="">
                  <template slot-scope="scope">
                    <span v-if="scope.row.domain" class="link" @click="openShop(scope.row)">
                      点击查看
                    </span>
                    <!-- <a style="color:#6c5dd3" :href="'http://'+(scope.row.domain&&scope.row.domain.includes(',')?scope.row.domain.split(',')[0]:scope.row.domain)" target="_blank"> 点击查看</a> -->
                  </template>
                </el-table-column>
                <el-table-column label="店铺简介" show-overflow-tooltip prop="introduction" min-width="150"></el-table-column>

              </el-table>
            </div>
            <div v-else style="height:600px;color: #999;text-align: center;font-size: 15px;line-height: 200px;">
              暂无数据
            </div>
          </div>
         

          <div class="center">
            <el-button @click="close()">取消</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')" :loading="loading">提交</el-button>
          </div>
        </el-form>
      </div>
      <!-- <moreSetting ref="moreSetting" @change="change"></moreSetting> -->
    </div>
  </el-dialog>

</template>

<script>
import formSubTit from "../../components/formSubTit.vue";
import selectBtn from "../../components/select-btn.vue";
import { countForSupplyFilter } from "@/api/system/user";
import { addPrice, getConfig, typeCount } from "@/api/info/rprice";
import gameListApi from "@/api/gameConfig/gameList";
export default {
  name: "supplyconfigDialog",
  components: { formSubTit, selectBtn },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      isEdit: false,
      supplyList: [],//表格当前展示的列表
      gameList: [], //游戏列表
      goodsNum: [],
      ruleForm: {
        gametype: "",
        supplyIdAddr: null, //表格当前展示的  选中的项
      },
      rules: [],
      supplyMine: "",
      curGame: {}, //当前游戏
      retailKey: "",
      retailName: "",
      otherShopAddress: "",
      allSupplyList: [],//总的 初始化时的列表
      supplyName:'',//供货人筛选
      // supplyIdAddr:[],
      tableSelectArr:[],//表格中已选中的项目 所有选中的项
      filterParams:{
        supplyName:'',
        isSelf:'',
        shoudong:''
      },
      maxNum:30,//货源最大可勾选数量
    };
  },
  mounted() {
    // this.getSupplyList();
    // this.getGameList();
  },
  computed: {
    allYouzhiMap() {
      return this.$store.getters.allYouzhiMap;
    },
    shopInfo() {
      return this.$store.getters.shopInfo;
    },
  },
  methods: {
    // 打开弹窗
    open(game, retailKey, retailName, otherShopAddress) {
      this.tableSelectArr = []
      this.supplyList = []
      this.retailKey = retailKey;
      this.retailName = retailName;
      this.otherShopAddress = otherShopAddress;
      this.curGame = { ...game };
      this.dialogVisible = true;
      this.$set(this.ruleForm, "gametype", this.curGame.id);
      this.getDetail();
      this.getMaxNum()
    },
    // 查询商户的货源数量限制
    async getMaxNum(){
      if(this.shopInfo&&this.shopInfo.huoyuannum){
        this.maxNum = this.shopInfo.huoyuannum
      }else{
        // 请求字典
        const res = await this.getDicts("sysTenantDefault")
        const obj = this.arrayToObject(res.data,'dictLabel')
        if(obj.huoyuanNum){
          this.maxNum = obj.huoyuanNum.dictValue||30
        }
      }

    },
    // 打开供货商的自营商城
    openShop(item) {
      if (item.domain && item.domain !== "0") {
        const url =
          "http://" +
          (item.domain && item.domain.includes(",")
            ? item.domain.split(",")[0]
            : item.domain);
        window.open(url);
      } else {
        return this.$message.error("该商家没有自营商城！");
      }
    },
    // 将当前展示的选中项 合并到总选中的项 数组
    // 当前展示的列表中没选中的项并且在总选中数组中的 从总选中项删掉
    curSelectToAllSelect(){
      const curTable = this.arrayToObject(this.supplyList,'tenant_id') 
      const curObj = this.arrayToObject(this.ruleForm.supplyIdAddr,'tenant_id') 
      const allSelectObj = this.arrayToObject(this.tableSelectArr,'tenant_id') 
      const allSelectObjNew = {...allSelectObj,...curObj}

      // 存在于当前表格 并且存在于总选中项数组 并且不存在于当前选中项，不加
      this.tableSelectArr = Object.keys(allSelectObjNew).map(key => {
        if(curTable[key]&&allSelectObj[key]&&!curObj[key]){
          // 从删除
          delete allSelectObjNew[key]
        }else{
          let obj = {...allSelectObjNew[key]}
          if(curTable[key]){
            obj = {...curTable[key]}
          }
          return obj
        }
      });
      this.tableSelectArr = this.tableSelectArr.filter(item => item != null)
    },
    // 重置筛选
    resetSearch(){
      this.filterParams = {
        supplyName:'',
        isSelf:'',
        shoudong:''
      }
      this.search()
    },
    // 搜索  筛选执行
    search(){
      // 将现选择的项合并到所有选择项
      this.curSelectToAllSelect()
      // 先将原始总表格和总已选择项 合并 已选择的项可能有新填写的内容
      const allSelectObj = this.arrayToObject(this.tableSelectArr,'tenant_id') 
      // 新的 所有供货商列表
      if(this.allSupplyList&&this.allSupplyList.length){
        this.allSupplyList.forEach(r=>{
          if(allSelectObj[r.tenant_id]){
            r = {
              ...r,...allSelectObj[r.tenant_id]
            }
          }
        })
      }
      
      if(this.filterParams.supplyName.trim()||this.filterParams.isSelf||this.filterParams.shoudong){
        this.supplyList = this.allSupplyList.filter(r=>{
          let flag = true
          if(this.filterParams.supplyName.trim()&&!r.tenant_name.includes(this.filterParams.supplyName.trim())){
            flag = false
          }
          if(this.filterParams.isSelf==1&&r.ifself1Cot<=0){
            flag = false
          }
          if(this.filterParams.isSelf==2&&r.ifself2Cot<=0){
            flag = false
          }
          if(this.filterParams.shoudong==1&&r.ziyingCot<=0){
            flag = false
          }
          if(this.filterParams.shoudong==2&&r.apiCot<=0){
            flag = false
          }
          return flag
        })
      }else{
        this.supplyList = JSON.parse(JSON.stringify(this.allSupplyList))
      }
      
      // 回显
      this.$nextTick(() => {
        console.log('回显')
        this.tableSelectArr.forEach((item) => {
          let flag = true;
          this.supplyList.forEach(async (row) => {
            if (
              (item.superId && item.superId == row.tenant_id) ||
              (item.tenant_id && item.tenant_id == row.tenant_id)
            ) {
              flag = false;
              this.$nextTick(() => {
                this.$refs.multipleTable.toggleRowSelection(row, true);
              });
            }
          });
          if (flag) {
            console.log("%c Line:222 🍺 flag", "color:#ffdd4d", flag);
          
          }
        });  
      });
      
      
    },
    // 设置表格的选择禁用行
    getDisabledRows(row) {
      if (
        row.tenant_id == this.$store.state.user.shopInfo.tenantId ||
        row.superId == this.$store.state.user.shopInfo.tenantId
      ) {
        return false;
      } else {
        return true;
      }
    },

    goSetting() {
      this.$refs.moreSetting.open();
    },

    getDetail() {
      if (!this.retailKey) {
        this.getSupplyList(true);
        return;
      }
      getConfig({
        gametype: this.ruleForm.gametype,
        retailKey: this.retailKey,
      })
        .then((res) => {
          // console.log("%c Line:132 🍎 getConfigres", "color:#3f7cff", res);
          // let arr = res.data.gametype.split(",");
          // let arr2 = [];
          // if (arr.length) {
          //   arr.forEach((r, i) => {
          //     arr2[i] = Number(r);
          //   });
          // }
          // this.$set(this.ruleForm, "gametype", arr2);
          // if(res.data&&res.data.length){
          //   this.retailKey = res.data[0].retailKey
          //   this.retailName = res.data[0].retailName
          // }
          this.ruleForm.supplyIdAddr = res.data;
     
          this.$forceUpdate();
          this.getSupplyList(true);
        })
        .catch((err) => {
          // //console.log("%c Line:138 🍔 err", "color:#33a5ff", err);
          // this.$set(this.ruleForm,'gametype',[])
          // this.ruleForm.supplyIdAddr = []
          this.getSupplyList(true);
        });
    },
    // 查询商品数量
    getMore(row) {
      let obj = {
        createId: row.tenant_id,
      };
      this.goodsNum = [];
      typeCount(obj).then((res) => {
        this.goodsNum = res.data;
      });
    },

    // 回显表格选中项
    async setCheck(supplyIdAddr) {
      let tempArr = [];
      if (supplyIdAddr) {
        this.ruleForm.supplyIdAddr = JSON.parse(supplyIdAddr);
        this.ruleForm.supplyIdAddr.forEach(async (item) => {
          let flag = true;
          this.supplyList.forEach(async (row) => {
            if (
              (item.superId && item.superId == row.tenant_id) ||
              (item.tenant_id && item.tenant_id == row.tenant_id)
            ) {
              flag = false;
              row.rrise = item.rrise || 0;
              row.gudingjiajia = item.gudingjiajia || 0;
              row.odr = item.odr || 1;
              row.accountType = item.accountType || "";
              row.ifself = item.ifself || "";
              item.tenant_id = item.superId || item.tenant_id;
              item.tenant_name =
                item.superName || item.tenantName || item.tenant_name;
              this.$nextTick(() => {
                this.$refs.multipleTable.toggleRowSelection(row, true);
              });
              if (item.tenant_id == this.$store.state.user.shopInfo.tenantId) {
                // row.isDisabled = true;
              }
            }
          });
          if (flag) {
            // 已选择的项目不在列表上 item
            ////console.log("%c Line:159 🍐 item", "color:#33a5ff", item);
            item.tenant_id = item.superId || item.tenant_id;
            item.tenant_name =
              item.superName || item.tenantName || item.tenant_name;
            item.cot = item.cot || 0;
            item.rrise = item.rrise || 0;
            item.gudingjiajia = item.gudingjiajia || 0;
            item.odr = item.odr || 1;
            item.accountType = item.accountType || 0;
            item.ifself = item.ifself || 3;
            this.supplyList.unshift(item);
            tempArr.push(item);
          }
        });

        // 将已选择但不在列表上的供货商选择上
        if (tempArr && tempArr.length) {
          tempArr.forEach((r) => {
            this.$refs.multipleTable.toggleRowSelection(r, true);
          });
        }
      }
      if(this.ruleForm.supplyIdAddr&&this.ruleForm.supplyIdAddr.length){
        this.tableSelectArr = JSON.parse(JSON.stringify(this.ruleForm.supplyIdAddr));
      }
      this.allSupplyList = JSON.parse(JSON.stringify(this.supplyList))
    },
    // 游戏列表
    // async getGameList() {
    //   let res = await gameListApi.getGameList();
    //   ////console.log("%c Line:278 🍫 res", "color:#465975", res);
    //   this.gameList = res.rows;
    // },
    async getGameList() {
      let res = await gameListApi.getGameListByCont();
      this.gameList = res.rows;
    },
    // 属性设置改变
    // change(e, gameId) {
    //   this.gameList.forEach((r) => {
    //     if (r.id == gameId) {
    //       r.content = e;
    //     }
    //   });
    //   this.getSupplyList();
    // },
    // 供货人列表
    getSupplyList(init) {
      this.supplyMine = null;
      if (this.ruleForm.gametype) {
        let obj = {
          gameIds: this.ruleForm.gametype,
        };
        let tempArr = JSON.parse(JSON.stringify(this.ruleForm.supplyIdAddr));
        ////console.log("%c Line:175 🍻 tempArr", "color:#fca650", tempArr);
        this.loading = true;
        countForSupplyFilter(obj).then((res) => {
          if (res.code == 200) {
            // res.data.sort((a, b) => {
            //   // this.allYouzhiMap[a.tenant_id] - this.allYouzhiMap[b.tenant_id]
            //   let c,d
            //   if(this.allYouzhiMap[a.tenant_id]){
            //     c=1
            //   }else{
            //     c=0
            //   }
            //   if(this.allYouzhiMap[b.tenant_id]){
            //     d=1
            //   }else{
            //     d=0
            //   }
            //   return c-d
            // })
            for (let i = 0; i < res.data.length; i++) {
              let r = res.data[i];
              r.gudingjiajia = 0;
              r.odr = 999;
              r.accountType = 3;
              r.ifself = 3;
              if (r.tenant_id == this.$store.state.user.shopInfo.tenantId) {
                // r.rrise = 0;
                // r.isDisabled = true;
                this.supplyMine = JSON.parse(JSON.stringify(r));
                res.data.splice(i, 1);
                i--;
              }
            }

            //将自己添加在供货商最前面并选中 this.supplyMine
            if (this.supplyMine) {
              // if (tempArr && tempArr.length) {
              //   tempArr.unshift(this.supplyMine);
              // } else {
              //   tempArr = [this.supplyMine];
              // }
              res.data.unshift(this.supplyMine);
            }
            // if(res.data&&res.data.length){
            //   res.data.forEach(r=>{
            //     r.gudingjiajia = 0
            //   })
            // }
            this.supplyList = res.data;
            this.$nextTick(() => {
              this.setCheck(JSON.stringify(tempArr));
            });
            this.loading = false;
          }
        });
      } else {
        // let tempArr = JSON.parse(JSON.stringify(this.ruleForm.supplyIdAddr))
        // this.supplyList = []
        // this.$nextTick(() => {
        //   this.setCheck(JSON.stringify(tempArr));
        // });
      }
    },
    // getSupplyList() {
    //   userGameCount().then(res => {
    //     if (res.code == 200) {
    //       res.data.forEach((r,i)=>{
    //         if(r.tenant_id==this.$store.state.user.shopInfo.tenantId){
    //           res.data.splice(i,1)
    //         }
    //       })
    //       this.supplyList = res.data;
    //       this.$nextTick(()=>{
    //         this.getDetail()
    //       })
    //     }
    //   });
    // },
    // 数值改变
    numchange(val, row) {
      if (val) {
        this.$refs.multipleTable.toggleRowSelection(row, true);
      }
    },
    handleSelectionChange(val) {
      this.ruleForm.supplyIdAddr = val;
    },
    isNumber(value) {
      return !isNaN(parseFloat(value)) && isFinite(value);
    },
    submitForm(formName) {
      if (!this.ruleForm.gametype || this.ruleForm.gametype.length == 0) {
        return this.$message.error("请选择游戏！");
      }
      this.curSelectToAllSelect()
      if(this.tableSelectArr.length&&this.tableSelectArr.length>this.maxNum){
        return this.$message.error(`最多可勾选${this.maxNum}个商家，您已勾选${this.tableSelectArr.length} ！`)
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let obj = {};
          obj.gametype = this.ruleForm.gametype;
          obj.retailKey = this.retailKey;
          obj.retailName = this.retailName;
          obj.otherShopAddress = this.otherShopAddress;
          let gudingjiajiaIsNumber = true;
          let odrIsNumber = true
          if (this.tableSelectArr && this.tableSelectArr.length) {
            console.log("%c Line:528 🍺 this.tableSelectArr", "color:#6ec1c2", this.tableSelectArr);
            // this.allSupplyList.forEach((row) => {
              
            // });
            this.tableSelectArr.forEach((item) => {
              if(item){
                item.superId = item.superId||item.tenant_id;
                  item.userId = item.userId||item.tenant_id;
                  item.superName = item.superName||item.tenant_name;
                  if (!this.isNumber(item.gudingjiajia)) {
                    row.gudingjiajia = 0;
                    gudingjiajiaIsNumber = false;
                  }
                  if (!this.isNumber(item.odr)) {
                    row.odr = 1;
                    odrIsNumber = false;
                  }
              }   
            });
          }
          if (!gudingjiajiaIsNumber) {
            return this.$message.error("固定加价金额请填写数字！");
          }
          if (!odrIsNumber) {
            return this.$message.error("排序请填写数字！");
          }
          obj.supplyIdAddrJson = this.tableSelectArr;
          this.loading = true;
          addPrice(obj)
            .then((response) => {
              this.loading = false;
              this.$modal.msgSuccess("操作成功！");
              this.$parent.getDetail();
              this.close();
              if (response.code == 200 && response.msg) {
                this.$emit("addSuccess", response.msg);
              }
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    close() {
      this.dialogVisible = false;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.ruleForm.id = this.info.id;
    },
  },
};
</script>
<style scoped lang="scss">
.supply-config-page {
  
  .subtit {
    margin: 20px 0;
  }
}
.center {
  text-align: center;
  margin-top: 15px;
}
::v-deep .el-dialog__body {
  max-height: calc(100vh - 60px) !important;
  overflow: hidden;
}
::v-deep .el-radio {
  margin-right: 15px;
}
::v-deep .el-input-number {
  width: 80px;
 text-align: left;
}

.supply-config-page .el-radio{
  width: 100px;
  text-align: left;
  margin: 5px 0;
}
</style>
